12. String Methods
String Methods
ND079 C1 L4 A12 String Method
Java provides advanced memory management for String objects by using a String pool. A String pool is a way of storing only one copy of a String.
To understand this, we have to look at what is happening in memory when we create Strings and assign them to variables. Strings in Java are immutable, meaning they cannot be changed after they are created. When we "change" the String in a variable, what actually happens is that, behind the scenes, Java creates a new String in the String pool—and changes the variable's reference value to point to this new String. The old String object may remain in place, unchanged.
Also note that multiple variables may use the same String reference. This means that if we have two variables with exactly the same String (e.g., "Hello"
) they will all reference the same String object.
String Pool Demonstration
The best way to understand string pools is to play with them in the code. In this next video, we will demonstrate the concept in IntelliJ.
ND079 C1 L4 A13 Memory Demo
SOLUTION:
- Multiple variables can point to the same String object.
- String are immutable.
SOLUTION:
The original String object is left unchanged (it still contains the string `"foo"`), but a new String object is created that contains the new String, `"bar"`.String Methods
ND079 C1 L4 A14 Method Demo
SOLUTION:
`text.contains("this");`Substring
ND079 C1 L4 A15 Substring Method